<template>
  <div>
    <!-- 1.编辑面包屑导航 -->
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
          </el-breadcrumb>
           <!-- 2.定义卡片标签 -->
                <el-card class="box-card">
                  <el-row :gutter="20">
                    <el-col :span="9">
                      <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable
                      @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                      </el-input>
                    </el-col>
                    <el-col :span="4">
                      <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
                    </el-col>
                  </el-row>
                   <el-table
                        :data="userList"
                        style="width: 100%"
                        stripe>
                        <el-table-column prop="id" label="ID">
                        </el-table-column>
                        <el-table-column prop="username" label="用户名">
                        </el-table-column>
                        <el-table-column prop="phone" label="电话">
                        </el-table-column>
                        <el-table-column prop="email" label="邮箱">
                        </el-table-column>
                        <el-table-column prop="status" label="状态">
                          <!-- 定义一个作用域插槽 -->
                          <template slot-scope="scope">
                            <!-- scope是封装后的对象  获取行级元素  row属性实现 -->
                            <el-switch
                            v-model="scope.row.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            @change="status(scope.row)">
                            </el-switch>
                          </template>
                        </el-table-column>
                        <el-table-column  label="操作">
                          <template slot-scope="scope">
                            <!-- scope是封装后的对象  获取行级元素  row属性实现 -->
                            <el-button type="primary" icon="el-icon-edit" size="small" @click="updateUser(scope.row)"></el-button>
                            <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteUser(scope.row)"></el-button>
                          </template>
                        </el-table-column>
                  </el-table>
                  <!--
                   size-change:当页面条数发生变化时触发
                   current-change:当页数改变时触发
                   current-page:显示当前的页数
                   page-size:初始每页条数
                   layout:显示分页的样式种类
                   total:总数
                   -->
                  <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryInfo.pageNum"
                        :page-sizes="[5, 10, 20, 40]"
                        :page-size="queryInfo.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                      </el-pagination>
                </el-card>
                <!--
                        :visible.sync  控制对话框是否展现
                      -->
                      <el-dialog
                        title="用户新增" :visible.sync="addUserDialogVisible" width="50%" @close="closeAddUserDialog">
                        <el-form :model="addUserForm" :rules="rules" ref="addUserRuleForm" label-width="100px" class="demo-ruleForm">
                                  <el-form-item label="用户名" prop="username">
                                    <el-input v-model="addUserForm.username"></el-input>
                                  </el-form-item>
                                  <el-form-item label="密码" prop="password">
                                    <el-input v-model="addUserForm.password" type="password"></el-input>
                                  </el-form-item>
                                  <el-form-item label="密码确认" prop="password2">
                                    <el-input v-model="addUserForm.password2" type="password"></el-input>
                                  </el-form-item>
                                  <el-form-item label="电话" prop="phone">
                                    <el-input v-model="addUserForm.phone"></el-input>
                                  </el-form-item>
                                  <el-form-item label="邮箱" prop="email">
                                    <el-input v-model="addUserForm.email"></el-input>
                                  </el-form-item>
                                </el-form>

                        <span slot="footer" class="dialog-footer">
                          <el-button @click="addUserDialogVisible = false">取 消</el-button>
                          <el-button type="primary" @click="addUserBtn">确 定</el-button>
                        </span>
                      </el-dialog>

                      <el-dialog
                        title="用户修改" :visible.sync="updateUserDialogVisible" width="50%" >
                        <el-form :model="updateUserForm" :rules="rules" ref="updateUserRuleForm" label-width="100px" class="demo-ruleForm">
                                  <el-form-item label="用户名" prop="username">
                                    <el-input v-model="updateUserForm.username" disabled></el-input>
                                  </el-form-item>
                                  </el-form-item>
                                  <el-form-item label="电话" prop="phone">
                                    <el-input v-model="updateUserForm.phone"></el-input>
                                  </el-form-item>
                                  <el-form-item label="邮箱" prop="email">
                                    <el-input v-model="updateUserForm.email"></el-input>
                                  </el-form-item>
                                </el-form>

                        <span slot="footer" class="dialog-footer">
                          <el-button @click="updateUserDialogVisible = false">取 消</el-button>
                          <el-button type="primary" @click="updateUserBtn">确 定</el-button>
                        </span>
                      </el-dialog>
  </div>
</template>

<script>
 // 导出，报告给vue我是一个组件
 export default {
    data(){
      //自定义规则位于data内，return外
      //rule：当前规则对象
      //value：要校验的的数据
      //callback：回调函数
      //校验邮箱规则
            const checkEmail = (rule, value, callback) => {
              //定义邮箱的正则表达式  JS中用/来表示正则表达式的开始和结束
              const emailRege = /^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/
              //.test方法可以将正则作为规则对value进行校验
              if (emailRege.test(value)) {
                //表示邮箱合法 正确返回
                return callback() //进行后续操作
              }
              callback(new Error('请填写正确的邮箱地址'))
            }

            //校验手机号的邮箱规则
            const checkPhone = (rule, value, callback) => {

              //定义校验手机号的正则语法
              const phoneRege = /^1[3-9][0-9]{9}$/
              if (phoneRege.test(value)) {

                return callback()
              }
              callback(new Error('请填写正确的手机号'))

            }
            const checkPassword = (rule, value, callback) => {

              if (value !== this.addUserForm.password) {

                return callback(new Error('两次密码不一致'))
              }
              callback()

            }
      return {
        //定义分页查询对象
        queryInfo: {
          query: '',  //关键字默认为null
          pageNum: 1, //默认第一页
          pageSize: 5  //默认5条
        },
        userList: [], //分页后的结果
        total: 0,     //总数
        addUserDialogVisible: false,
        updateUserDialogVisible: false,
        //设定新增用户的对象
                addUserForm: {
                  username: '',
                  password: '',
                  password2:  '',
                  phone:  '',
                  email:  ''
                },
                updateUserForm: {},
                rules: {
                   username: [
                              { required: true, message: '请输入用户名', trigger: 'blur' },
                              { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
                            ],
                   password: [
                              { required: true, message: '请输入密码', trigger: 'blur' },
                              { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
                            ],
                   password2: [
                            { required: true, message: '请再次输入密码', trigger: 'blur' },
                            { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
                            {validator: checkPassword,trigger:'blur'}
                   ],
                   phone: [
                              { required: true, message: '请输入电话', trigger: 'blur' },
                              { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' },
                              {validator: checkPhone,trigger:'blur'}
                            ],
                   email: [
                              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                              { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
                              {validator: checkEmail,trigger:'blur'}
                            ],


                }
      }
    },
    //页面加载完成后调用
    mounted(){
        this.getUserList()
    },
    methods: {
        //动态获取userList数据
        async getUserList(){
          const {data:result} = await this.$http.get('/user/list',{
            //get请求参数传递最常用之方法
            //params后跟一个对象,queryInfo本就是对象
            params: this.queryInfo
            })
        if(result.status != 200) return this.$message.error('获取列表失败！')
        //为前端页面total赋值
        this.total = result.data.total
        //为前端页面userList赋值
        this.userList = result.data.rows
        },
        //配置页面条数改变时触发的方法
        handleSizeChange(pageSize){
          //查询条件需要变化
          this.queryInfo.pageSize = pageSize
          //重新查询数据
          this.getUserList()
        },
        handleCurrentChange(pageNum){
          this.queryInfo.pageNum = pageNum
          this.getUserList()
        },
        async status(row){
          //模板字符串写法 `` 可以编辑多行,可以直接对象取值${key}
                  //es6的高端写法
            const {data:result} = await this.$http.put(`/user/status/${row.id}/${row.status}`)
            if(result.status!=200) return this.$message.error('更新操作失败！')
            this.$message.success('更新操作成功！')
        },
        handleClose(done) {
                this.$confirm('确认关闭？')
                  .then(_ => {
                    done();
                  })
                  .catch(_ => {});
              },
        closeAddUserDialog(){
          this.$refs.addUserRuleForm.resetFields()
        },
        addUserBtn(){
          //重新校验一次表单
          //1.获取表单对象
          //2.进行数据校验
          //会触发刚才定义的所有的rule，返回true
          this.$refs.addUserRuleForm.validate(async valid => {
            if(!valid) return this.$message.error('请填写所有字段！')
            //发起ajax请求，实现新增
           const {data:result} = await this.$http.post('/user/addUser',this.addUserForm)
           if(result.status !== 200) return this.$message.error('新增用户失败！')
           this.$message.success('新增用户成功！')
          })
          this.addUserDialogVisible = false
          //刷新列表
          this.getUserList()
        },
        async deleteUser(user){
          //返回的是promise对象，可以async-await
          const result = await this.$confirm(`此操作将永久删除用户${user.username},是否继续？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).catch(error => error)
          if(result !== 'confirm') return this.$message.info('用户取消操作')
          //ajax请求
          const {data:resultDB} = await this.$http.delete(`/user/${user.id}`)
          this.$message.success('用户删除成功！')
          //页面重新加载
          this.getUserList()
        },
        //点击更新触发
        updateUser(user){
          //数据回显
          this.updateUserForm = user
          //打开对话框
          this.updateUserDialogVisible = true
        },
        //更新页面点击确定触发
        updateUserBtn(){
          //数据提交时校验
          this.$refs.updateUserRuleForm.validate(async valid => {
            if(!valid) return this.$message.error('请填写所有字段！')
            //发送请求
            const {data:result} = await this.$http.put('/user/updateUser',this.updateUserForm)
            if(result.status !== 200) return this.$message.error('修改角色信息失败')
            this.$message.success('修改角色信息成功')

          })
          //关闭对话框
          this.updateUserDialogVisible = false
          //重新加载表格
          this.getUserList()
        }
    }
 }
</script>

<style>

</style>
